<template>
	<view class="container">
		<u-navbar placeholder :safeAreaInsetTop="false" :statusbarTop="vuex_statusBarHeight+8">
			<view class="u-nav-slot" slot="left">
				<view class="sLeft dfx alc">
					<u-avatar :src="vuex_userInfo.face" size="40"></u-avatar>
					<text class="ml15 fs40">AI直播</text>
				</view>
			</view>
			<view class="u-nav-slot" slot="right">
				<!-- <u-icon name="plus-circle-fill" size="28" color="#fff" @click="add()"></u-icon> -->
				<image src="@/static/img/index/search.png" style="width: 56rpx;height: 56rpx;" @click="add()"></image>
			</view>
		</u-navbar>

		<view class="setting" @click="toset"></view>

		<view class="liveFlow mt80">
			<view class="df alc wrap space">
				<view class="item mb30 f1" @click="$tools.navTo('openLive/trick/index')">
					<image src="@/static/img/live/num1.png" mode=""></image>
				</view>
				<view class="item mb30 f2" @click="$tools.navTo('openLive/interaction/index')">
					<image src="@/static/img/live/num2.png" mode=""></image>
				</view>
				<view class="item mb30 f3" @click="$tools.navTo('openLive/explain/index')">
					<image src="@/static/img/live/num3.png" mode=""></image>
				</view>
				<view class="item mb30 f4" @click="$tools.navTo('openLive/live/live')">
					<image src="@/static/img/live/num4.png" mode=""></image>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				userInfo: {
					avatar: '../../static/mine/hot.png'
				},
				roomId: '12',
				play: false,
				isAI: true,
				showOld: false,
				list: [],
				msgArr: [],
				socket: null,
				liveSetting: {},
				bgAudioManager: null,
				cur: 0,
				activeAudio: {},
				liveInfo: {},
				alist: [],
				audioList: [],
				keywordList: [],
				problem: '',
				recover: '',
				baseUrl: '',
				cookieKS: '',
				cookieDY: '',
				timer: null,
				reload: false,
				isplay: false,
				msgList: [],
				msgInfo: {},
				inter: null
			};
		},
		watch: {
			msgList(nval, oval) {
				console.log('val', nval, oval);
			}
		},
		onShow() {
			// 
			if (uni.getStorageSync('openLive')) {
				uni.removeStorageSync('openLive')
				this.init()
			}
			if (uni.getStorageSync('liveSetting')) {
				this.showOld = true
			}
		},
		mounted() {
			uni.createSelectorQuery().select('.u-navbar').boundingClientRect(data => {
				this.$tn.vuex('vuex_navbarHeight', data.bottom);
				this.$tn.vuex('vuex_contentHeight',this.vuex_windowHeight-this.vuex_navbarHeight);
			}).exec();
		},
		methods: {
			init() {
				this.liveSetting = JSON.parse(uni.getStorageSync('liveSetting'))
				console.log('info', this.liveSetting);
				if (this.liveSetting.roomId) {
					let params = {
						type: 'start',
						live_id: this.liveSetting.roomId,
						scheme_id: this.liveSetting.optionId,
						platform: this.liveSetting.actions,
						is_random: this.liveSetting.isSequence
					}
					this.$api.addLiveData(params).then(res => {
						if (res.code == '200') {
							this.initWs()
							this.getLive()
						} else {
							this.$tools.toast(res.msg, 2000);
						}
					})
				}
			},
			toset() {
				uni.navigateTo({
					url: '/pages/openLive/setlive'
				})
			},
			playAudio(r) {
				this.isAI = !this.isAI
				if (r) {
					this.bgAudioManager.play()
				} else {
					this.bgAudioManager.pause()
				}
			},
			getLive() {
				let params = {
					id: this.liveSetting.optionId
				}
				this.$api.info(params).then(res => {
					console.log(res);
					if (res.code == 200) {
						this.alist = []
						this.audioList = []
						this.liveInfo = res.data.explainsData
						if (res.data.explainsData.length < 1) {
							this.$tools.toast('该直播方案下暂无讲解音频，请添加后开播！', 2000);
							this.close()
						}
						res.data.explainsData.map(i => {
							i.audio_urls.map(j => {
								if (j.url != '') {
									let obj = {
										src: j.url,
										isexplan: true,
										explainId: i.id,
										explainName: i.name,
										index: i.index
									}
									this.alist.push(obj)
									this.audioList.push(obj)
								}
							})
						})
						if (this.alist.length == 1) {
							this.$tools.toast('开播时直播方案内需要最少两条商品讲解，请添加后开播！', 2000);
						} else {
							this.playAudit()
						}
					}
				})
			},

			setTimer() {
				this.timer = setInterval(() => {
					this.reload = true
				}, 12000)
			},

			playAudit() {
				// this.bgAudioManager = uni.getBackgroundAudioManager();
				this.bgAudioManager = uni.createInnerAudioContext();
				this.bgAudioManager.autoplay = false
				this.cur = 0
				console.log('原始列表', this.alist);
				this.bgAudioManager.src = this.audioList[this.cur].src;
				this.activeAudio = this.audioList[this.cur]
				this.bgAudioManager.play()
				this.bgAudioManager.onEnded(() => {
					if (this.isplay) this.isplay = false
					// let time = this.liveSetting.playNext > 1 ? this.liveSetting.playNext * 1000 : 500
					// setTimeout(() => {
					console.log('播放结束,当前索引：', this.cur);
					this.problem = ''
					this.recover = ''
					this.cur++
					if (this.cur >= this.audioList.length) {
						console.log('音频列表重置');
						this.cur = 0
						this.audioList = []
						this.audioList.push(...this.alist)
						console.log('重置后的列表', this.audioList);
					}
					this.bgAudioManager.src = this.audioList[this.cur].src;
					this.bgAudioManager.play()
					this.activeAudio = this.audioList[this.cur]
					// console.log('直播间配置信息：', this.liveSetting);
					if (this.liveSetting.showProduct !== 'none' && this.audioList[this.cur].index != '' && this.audioList[this
							.cur].isexplan) {
						this.$tools.toast('正在更新直播间商品弹框');
						uni.setStorageSync('showProduct', this.liveSetting.showProduct)
						if (this.liveSetting.showProduct == 'carProduct') {
							uni.setStorageSync('current1', this.audioList[this.cur].index)
						} else if (this.liveSetting.showProduct == 'liveProduct') {
							uni.setStorageSync('current', this.audioList[this.cur].index)
						}
						this.$tools.navTo('webview/webview')
					}
					// }, time)
				})
			},

			initWs() {
				this.baseUrl = ''
				this.$api.wsUrl().then(res => {
					if (res.code == '200') {
						console.log(res.data, 111);
						switch (this.liveSetting.actions) {
							case '抖音':
								if (res.data.ws_douyin == '') {
									this.$tools.toast('抖音直播间正在维护中，暂时无法使用 ', 2000);
									this.close()
									return;
								} else {
									// this.baseUrl = res.data.ws_douyin + '//' + this.liveSetting.roomId
									this.baseUrl = res.data.ws_douyin
								}
								break;
							case '快手':
								if (res.data.ws_kuaishou == '') {
									this.$tools.toast('快手直播间正在维护中，暂时无法使用 ', 2000);
									this.close()
									return;
								} else {
									this.baseUrl = res.data.ws_kuaishou
								}
								break;
							case 'tiktok':
								if (res.data.ws_kuaishou == '') {
									this.$tools.toast('tiktok直播间正在维护中，暂时无法使用 ', 2000);
									this.close()
									return;
								} else {
									this.baseUrl = res.data.ws_tiktok + '/' + this.liveSetting.roomId
								}
								break;
							default:
								break;
						}
						this.cookieKS = res.data.kuaishou_cookie
						this.cookieDY = res.data.douyin_cookie
						if (this.baseUrl != '') {
							this.creatSocket()
						}
					}
				})
			},

			creatSocket() {
				uni.showLoading({
					title: '正在获取直播间'
				});
				uni.connectSocket({
					url: this.baseUrl,
				});
				uni.onSocketOpen((res) => {
					let actions = this.liveSetting.actions
					if (actions == '抖音' || actions == '快手') {
						let data = {
							url: actions == '快手' ? 'https://live.kuaishou.com/u/' + this.liveSetting.roomId :
								'https://live.douyin.com/' + this.liveSetting.roomId,
							cookie: actions == '快手' ? this.cookieKS : this.cookieDY
						}
						console.log(this.liveSetting);

						uni.sendSocketMessage({
							data: JSON.stringify(data)
						});
						console.log(this.baseUrl, this.cookieDY);
						console.log(11111111111, data);
						this.inter = setInterval(() => {
							uni.sendSocketMessage({
								data: 'ping'
							});
						}, 120000)
					}
				});

				uni.onSocketError((res) => {
					console.log('onSocketError', res);
					uni.hideLoading()
				});
				uni.onSocketClose((res) => {
					uni.hideLoading()
					if (this.msgInfo.tips == '未开播') {
						this.$tools.toast('检测到该房间号未开播，请检查房间号是否正确！', 2000);
						this.close()
					}
					if (this.msgInfo.tips == "获取roomid失败'room'") {
						this.$tools.toast('直播间获取失败，请检查房间号是否正确！', 2000);
						this.close()
					}
					clearInterval(this.inter)
					console.log('WebSocket 已关闭！', res, this.liveSetting.roomId);
					setTimeout(() => {
						if (this.liveSetting.roomId) {
							console.log('重连');
							uni.connectSocket({
								url: this.baseUrl
							});
						}
					}, 100)
				});

				uni.onSocketMessage((res) => {
					uni.hideLoading()
					let data = JSON.parse(res.data)
					console.log('data', data, data.tips);
					this.msgInfo = data
					let scrolling = [];

					if (data.tips == '获取roomid成功' || data.tips == '获取参数成功') {
						this.$tools.toast('直播间获取成功！', 2000);
					}

					if (this.liveSetting.actions == '快手' && data.result?.commentFeeds) {
						data.result.commentFeeds.map(i => {
							scrolling.push({
								name: i.user.userName,
								content: i.content
							})
						})
					} else if (this.liveSetting.actions == '抖音') {
						let obj = {}
						console.log(data.common.method, 11111111);
						switch (data.common.method) {
							case 'WebcastChatMessage':
								obj = {
									name: data.user.nickName,
									content: data.content
								}
								scrolling.push(obj)
								break;
							case 'WebcastMemberMessage':
								obj = {
									name: data.user.nickName,
									content: '来了'
								}
								scrolling.push(obj)
								break;
							case 'WebcastLikeMessage':
								obj = {
									name: data.user.nickName,
									content: '点赞' + data.count + '次'
								}
								scrolling.push(obj)
								break;
							default:
								break;
						}
					}


					if (scrolling.length > 0) {
						this.msgArr.push(...scrolling)


						let params = {
							type: 'proceed',
							explain_id: this.activeAudio.explainId || '',
							explain_name: this.activeAudio.explainName || '',
							message_list: this.liveSetting.actions == '快手' ? JSON.stringify(data.result) : JSON.stringify(data)
							// message_list: JSON.stringify(data.result): data.message_list
						}
						this.$api.addLiveData(params).then(res => {
							if (res.code == '200') {
								if (res.data.length > 0 && this.audioList[this.cur].isexplan && res.data[0].audio_url != '' &&
									!this.isplay) {
									console.log('res', res);
									this.isplay = true
									this.audioList.shift()
									this.cur -= 1
									if (this.cur < 0) this.cur = 0
									this.audioList.splice(this.cur + 1, 0, {
										src: res.data[0].audio_url,
										isexplan: false
									})
									// 处理互动音频播放
									let time = this.liveSetting.playInteract * 1000
									let timer = setTimeout(() => {
										console.log('play');
										this.problem = res.data[0].keywords
										this.recover = res.data[0].interact_name
										this.cur++
										this.bgAudioManager.src = this.audioList[this.cur].src;
										this.bgAudioManager.play()
										this.activeAudio = this.audioList[this.cur]
										console.log('index', this.cur);
										console.log('timer', timer);
										clearTimeout(timer)
										console.log('timer1', timer);
									}, time)
									// 处理互动音频播放结束
								}
							}
						})
					}
				});
			},

			close() {
				let params = {
					type: 'end'
				}
				console.log('params', params);
				this.$api.addLiveData(params).then(res => {
					console.log('res', res);
					// clearInterval(this.timer)
					this.liveSetting = {}
					this.msgArr = []
					this.bgAudioManager.stop()
					this.bgAudioManager.src = ''
					uni.closeSocket()
					uni.removeStorageSync('openLive')
				})
			}
		},
	}
</script>

<style lang="less">
	/deep/.u-navbar__content {
		background: linear-gradient(45deg, #eaf5fe, #eff3fe) !important;
	}

	/deep/.u-icon--left {
		align-items: flex-start !important;
	}

	.container {
		height: 100%;
		overflow: hidden;
	}

	.setting {
		height: 200rpx;
		margin: 30rpx;
		margin-top: 50rpx;
		color: #081e5b;
		border-radius: 16rpx;
		background: url("../../static/img/live/live_pic.png") no-repeat;
		background-size: cover;


		.live {
			font-size: 38rpx;
			font-weight: bold;
		}
	}

	.liveFlow {
		.item {
			width: 328rpx;
			height: 400rpx;
			border-radius: 40rpx;
			text-align: right;

			image {
				width: 116rpx;
				height: 116rpx;
				margin-top: 20rpx;
			}
		}

		.f1 {
			background: url('@/static/img/live/f1.png') no-repeat;
			background-size: contain;
		}

		.f2 {
			background: url('@/static/img/live/f2.png') no-repeat;
			background-size: contain;
		}

		.f3 {
			background: url('@/static/img/live/f3.png') no-repeat;
			background-size: contain;
		}

		.f4 {
			background: url('@/static/img/live/f4.png') no-repeat;
			background-size: contain;
		}
	}


	.listBox {
		background: #f1f3f4;
		border-radius: 16rpx;
		color: #000;

		.litem {
			// margin-bottom: 16rpx;
			background: #fff;
			// border-radius: 16rpx;
			padding: 20rpx;
			flex-wrap: wrap;
			border-bottom: 2px solid #f5f5f5;

			.main {
				width: 80%;
			}

			.replay {
				width: 10%;
				font-size: 26rpx;
				border-radius: 16rpx;
				border: 1px solid #308ffc;
				padding: 0rpx 10rpx;
				text-align: center;
				height: 45rpx;
			}
		}
	}

	/deep/.u-form-item,
	/deep/.u-form-item__body__left__content__label {
		color: #fff !important;
	}

	/deep/.u-input {
		background: transparent !important;
	}
</style>